<template>
  <view class="sheep-game">
    <!-- 顶部信息栏 -->
    <view class="game-header">
      <view class="level">关卡: {{currentLevel}}</view>
      <view class="steps">剩余步数: {{remainingSteps}}</view>
    </view>
    
    <!-- 游戏主区域 -->
    <view class="game-container">
      <!-- 游戏卡片区 -->
      <view class="cards-area" :style="{ height: areaHeight + 'px' }">
        <view 
          v-for="(card, index) in visibleCards" 
          :key="card.id"
          class="card"
          :class="{
            'selected': selectedCards.includes(card),
            'blocked': isCardBlocked(card)
          }"
          :style="getCardStyle(card)"
          @tap="handleCardClick(card)"
        >
          <game-icons :type="card.type"/>
        </view>
      </view>
      
      <!-- 底部卡槽区 -->
      <view class="slot-area">
        <view 
          v-for="(card, index) in slotCards" 
          :key="index"
          class="slot-card"
        >
          <game-icons v-if="card" :type="card.type"/>
        </view>
      </view>
    </view>
    
    <!-- 游戏控制按钮 -->
    <view class="control-panel">
      <button class="control-btn" @tap="restartLevel">重新开始</button>
      <button class="control-btn" @tap="shuffleCards">洗牌</button>
      <button class="control-btn" @tap="rollback" :disabled="!canRollback">撤销</button>
    </view>
  </view>
</template>

<script>
import GameIcons from '../../components/game-icons.vue'

const CARD_TYPES = ['sheep', 'wolf', 'carrot', 'house', 'tree', 'grass']
const SLOT_SIZE = 7
const MAX_LAYER = 5

export default {
  components: {
    GameIcons
  },
  data() {
    return {
      currentLevel: 1,
      remainingSteps: 30,
      cards: [], // 所有卡片
      visibleCards: [], // 可见卡片
      selectedCards: [], // 已选卡片
      slotCards: new Array(SLOT_SIZE).fill(null), // 底部卡槽
      history: [], // 操作历史
      areaHeight: 600,
      shuffleCount: 3 // 剩余洗牌次数
    }
  },
  
  computed: {
    canRollback() {
      return this.history.length > 0
    }
  },
  
  onLoad() {
    this.initGame()
  },
  
  methods: {
    initGame() {
      this.generateCards()
      this.layoutCards()
      this.resetGameState()
    },
    
    resetGameState() {
      this.selectedCards = []
      this.slotCards = new Array(SLOT_SIZE).fill(null)
      this.history = []
      this.remainingSteps = 30
      this.shuffleCount = 3
    },
    
    generateCards() {
      this.cards = []
      let id = 0
      
      // 生成卡片，确保每种类型都是3的倍数
      CARD_TYPES.forEach(type => {
        for(let i = 0; i < 9; i++) {
          this.cards.push({
            id: id++,
            type,
            x: 0,
            y: 0,
            layer: 0,
            blocked: false
          })
        }
      })
      
      // 随机打乱卡片顺序
      this.cards = this.shuffleArray(this.cards)
    },
    
    layoutCards() {
      const gridSize = 80 // 卡片大小
      const overlap = 20 // 卡片重叠距离
      const basePositions = []
      
      // 生成基础位置网格
      for(let i = 0; i < 8; i++) {
        for(let j = 0; j < 6; j++) {
          basePositions.push({
            x: j * (gridSize - overlap),
            y: i * (gridSize - overlap)
          })
        }
      }
      
      // 随机分配位置和层级
      this.cards.forEach((card, index) => {
        const pos = basePositions[index % basePositions.length]
        card.x = pos.x + Math.random() * 20 - 10 // 添加随机偏移
        card.y = pos.y + Math.random() * 20 - 10
        card.layer = Math.floor(index / basePositions.length)
      })
      
      this.updateVisibleCards()
    },
    
    updateVisibleCards() {
      // 更新卡片的可见性和阻塞状态
      this.visibleCards = this.cards.filter(card => !card.removed)
      this.updateBlockedStatus()
    },
    
    updateBlockedStatus() {
      // 检查每张卡片是否被其他卡片覆盖
      this.visibleCards.forEach(card => {
        card.blocked = this.isCardBlocked(card)
      })
    },
    
    isCardBlocked(card) {
      // 检查卡片是否被上层卡片覆盖
      return this.visibleCards.some(other => {
        if(other.layer <= card.layer) return false
        
        // 检查是否有重叠
        const overlap = !(
          other.x + 80 < card.x ||
          other.x > card.x + 80 ||
          other.y + 80 < card.y ||
          other.y > card.y + 80
        )
        
        return overlap
      })
    },
    
    handleCardClick(card) {
      if(card.blocked) return
      
      const index = this.selectedCards.indexOf(card)
      if(index !== -1) {
        // 取消选中
        this.selectedCards.splice(index, 1)
      } else {
        // 选中卡片
        this.selectedCards.push(card)
        
        // 检查是否可以消除
        if(this.selectedCards.length === 3) {
          if(this.canEliminate()) {
            this.eliminateCards()
          } else {
            // 移动到卡槽
            this.moveToSlot()
          }
        }
      }
    },
    
    canEliminate() {
      // 检查是否同类型
      return this.selectedCards.every(card => 
        card.type === this.selectedCards[0].type
      )
    },
    
    eliminateCards() {
      // 保存操作历史
      this.saveHistory()
      
      // 移除卡片
      this.selectedCards.forEach(card => {
        card.removed = true
      })
      
      this.selectedCards = []
      this.updateVisibleCards()
      this.remainingSteps--
      
      // 检查游戏状态
      this.checkGameState()
    },
    
    moveToSlot() {
      // 查找空槽位
      const emptySlot = this.slotCards.indexOf(null)
      if(emptySlot === -1) {
        // 槽位已满，游戏结束
        this.gameOver()
        return
      }
      
      // 保存操作历史
      this.saveHistory()
      
      // 移动到槽位
      const card = this.selectedCards.pop()
      card.removed = true
      this.slotCards[emptySlot] = card
      
      this.updateVisibleCards()
      this.remainingSteps--
      
      // 检查游戏状态
      this.checkGameState()
    },
    
    checkGameState() {
      if(this.visibleCards.length === 0) {
        // 通关
        this.levelComplete()
      } else if(this.remainingSteps <= 0) {
        // 步数用完
        this.gameOver()
      }
    },
    
    levelComplete() {
      uni.showModal({
        title: '恭喜',
        content: '完成本关！',
        showCancel: false,
        success: () => {
          this.currentLevel++
          this.initGame()
        }
      })
    },
    
    gameOver() {
      uni.showModal({
        title: '游戏结束',
        content: '步数用完了！',
        showCancel: false,
        success: () => {
          this.restartLevel()
        }
      })
    },
    
    restartLevel() {
      this.initGame()
    },
    
    shuffleCards() {
      if(this.shuffleCount <= 0) {
        uni.showToast({
          title: '洗牌次数已用完',
          icon: 'none'
        })
        return
      }
      
      // 保存操作历史
      this.saveHistory()
      
      // 重新排列可见卡片
      const visibleCards = this.visibleCards.slice()
      this.shuffleArray(visibleCards).forEach((card, index) => {
        const original = this.visibleCards[index]
        card.x = original.x
        card.y = original.y
        card.layer = original.layer
      })
      
      this.shuffleCount--
      this.updateVisibleCards()
    },
    
    rollback() {
      if(!this.canRollback) return
      
      const previousState = this.history.pop()
      this.cards = previousState.cards.map(card => ({...card}))
      this.slotCards = [...previousState.slotCards]
      this.remainingSteps = previousState.remainingSteps
      this.updateVisibleCards()
    },
    
    saveHistory() {
      this.history.push({
        cards: this.cards.map(card => ({...card})),
        slotCards: [...this.slotCards],
        remainingSteps: this.remainingSteps
      })
    },
    
    shuffleArray(array) {
      const newArray = [...array]
      for(let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
      }
      return newArray
    },
    
    getCardStyle(card) {
      return {
        transform: `translate(${card.x}px, ${card.y}px)`,
        zIndex: card.layer
      }
    },
    
    getCardImage(type) {
      return `/static/images/sheep/${type}.png`
    }
  }
}
</script>

<style lang="less">
@import '../../styles/uni.less';

.sheep-game {
  min-height: 100vh;
  background-color: @bg-color;
  padding: @spacing-md;
  
  .game-header {
    display: flex;
    justify-content: space-between;
    padding: @spacing-md;
    background-color: @bg-color-grey;
    border-radius: @border-radius-md;
    margin-bottom: @spacing-lg;
    
    .level, .steps {
      font-size: @font-size-lg;
      color: @text-color;
      font-weight: bold;
    }
  }
  
  .game-container {
    .cards-area {
      position: relative;
      background-color: @bg-color-grey;
      border-radius: @border-radius-md;
      margin-bottom: @spacing-lg;
      overflow: hidden;
      
      .card {
        position: absolute;
        width: 80px;
        height: 80px;
        background-color: @bg-color;
        border-radius: @border-radius-sm;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: all 0.3s;
        
        &.selected {
          transform: scale(1.1) translateY(-10px);
          box-shadow: 0 4px 12px rgba(0,0,0,0.2);
          border: 2px solid @primary-color;
        }
        
        &.blocked {
          opacity: 0.7;
          pointer-events: none;
        }
        
        image {
          width: 100%;
          height: 100%;
          padding: @spacing-sm;
        }
      }
    }
    
    .slot-area {
      display: flex;
      justify-content: center;
      gap: @spacing-sm;
      padding: @spacing-md;
      background-color: @bg-color-grey;
      border-radius: @border-radius-md;
      
      .slot-card {
        width: 60px;
        height: 60px;
        background-color: fade(@text-color, 10%);
        border-radius: @border-radius-sm;
        display: flex;
        align-items: center;
        justify-content: center;
        
        image {
          width: 80%;
          height: 80%;
        }
      }
    }
  }
  
  .control-panel {
    display: flex;
    justify-content: center;
    gap: @spacing-lg;
    margin-top: @spacing-xl;
    
    .control-btn {
      background-color: @primary-color;
      color: #fff;
      padding: @spacing-sm @spacing-xl;
      border-radius: @border-radius-md;
      font-size: @font-size-md;
      
      &:active {
        opacity: 0.8;
      }
      
      &[disabled] {
        background-color: @bg-color-grey;
        color: @text-color-light;
      }
    }
  }
}
</style> 